import React, { Component } from 'react';
import {
  StyleSheet, View, ScrollView, DeviceEventEmitter, TouchableWithoutFeedback, TouchableOpacity, Image, Alert,
} from 'react-native';
import { Text } from 'native-base';
import Icon from 'react-native-vector-icons/AntDesign';
import { produce } from 'immer';
import ZlstIcon from '../../../components/zlst-icons';
import Theme from '../../../native-base-theme/variables/commonColor';
import { UtilToast } from '../../../utils/util-method';
import * as todoService from '../../../services/todo';
import SelectPart from '../../../components/selectIncidentpart';
import { FormTextChoice, FormText, FormSearchChoiceChange, FormInputPop, FormInputWithName, FormTextarea } from '../../../components';

class AddPosition extends Component {
  static navigationOptions = {
    title: '添加临时位置',
    headerStyle: { backgroundColor: Theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  constructor(props) {
    super(props);
    this.state = {
      showSelectIncidentPart: false, // 展示故障位置选择
      modalVisible: false, // 选择物料
      fatherPosition: { id: '', name: '上级位置', value: '', splitCode: '' },
      material: { id: '', name: '上级位置', value: '', materialName: '' },
      tempCode: '',
      tempDesc: '',
    };
  }

  componentDidMount() {
    const { upPart } = this.props.navigation.state.params;
    this.setState(produce(draft => {
      draft.material.id = upPart.materialId;
      draft.material.value = upPart.materialCode;
      draft.material.materialName = upPart.materialName;
    }));
  }

  confirmSub = () => {
    if (this.state.tempCode == '') {
      UtilToast('请输入临时位置编码', 'danger');
    } else if (this.state.tempDesc == '') {
      UtilToast('请输入临时位置描述', 'danger');
    } else if (this.state.material.value == '') {
      UtilToast('请输入选择安装物料', 'danger');
    } else {
      Alert.alert(
        '提示',
        '确定提交',
        [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
            onPress: () => {
              this.submit();
            },
          },
        ],
      );
    }
  }

  choiceFatherPosition = () => {
    this.setState({
      showSelectIncidentPart: true,
    });
    // const a = Math.random().toString().slice(-6);
  }

  _hideSelect = () => {
    this.setState({
      showSelectIncidentPart: false,
    });
  }

  _finishSelectPart = async (selectedList) => { // 故障位置选择结束
    if (selectedList && selectedList.length) {
      const material = selectedList[selectedList.length - 1];
      this.setState(produce(draft => {
        draft.fatherPosition.id = material.splitItemId;
        draft.fatherPosition.value = material.description;
        draft.fatherPosition.splitCode = material.splitCode;
        draft.tempCode = material.splitCode;
      }));
    }
  }

  submit = async () => {
    const mParams = this.props.navigation.state.params;
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const params = {
        objType: mParams.equipObjType,
        splitCode: this.state.tempCode,
        parentId: this.state.fatherPosition.id,
        parentCode: this.state.fatherPosition.splitCode,
        description: this.state.tempDesc,
        materialId: this.state.material.id,
        materialCode: this.state.material.value,
        materialName: this.state.material.materialName,
      };
      const data = await todoService.addPosition(params);
      DeviceEventEmitter.emit('showLoading', false);
      if (data) {
        UtilToast('提交成功', 'success');
        this.props.navigation.goBack();
        mParams._refresh();
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  _cancelModal = () => {
    this.setState({ modalVisible: false });
  }

  _showModal = () => {
    this.setState({
      modalVisible: true,
    });
  }

  searchUri = '';

  searHeaderTitle = '请选择';

  searchNoHeader = false;

  _choiceConfirm = null;

  extraInfo = {};

  choiceMaterial = () => {
    this._choiceConfirm = (it) => {
      this.setState(produce(draft => {
        draft.material.id = it[0].id;
        draft.material.value = it[0].code;
        draft.material.materialName = it[0].name;
      }));
    };
    this.searchUri = `${todoService.serverName}/materialDefinition/lists`;
    this.searHeaderTitle = '请选择物料信息';
    this.searchNoHeader = false;
    this.extraInfo = {};
    this._showModal();
  }

  render() {
    const { equipObjType, equipmentId } = this.props.navigation.state.params;
    return (
      <View style={styles.container}>
        <View>
          {this.state.modalVisible && (
            <FormSearchChoiceChange
              onClose={this._cancelModal}
              searchUri={this.searchUri}
              extraInfo={this.extraInfo}
              type="radio"
              title={this.searHeaderTitle}
              searchNoHeader={this.searchNoHeader}
              choiceConfirm={this._choiceConfirm}
            />
          )}
          {this.state.showSelectIncidentPart && (
            <SelectPart
              show={this.state.showSelectIncidentPart}
              hide={this._hideSelect}
              equTypeId={equipObjType}
              equipmentId={equipmentId}
              finish={this._finishSelectPart}
            />
          )}
        </View>
        <ScrollView style={{ flex: 1 }}>
          <View>
            <FormTextChoice name={this.state.fatherPosition.name} value={this.state.fatherPosition.value} choiceMethod={this.choiceFatherPosition} />
            <Text style={{ marginLeft: 8, color: 'red' }}>(提示：不选上级位置默认为顶级)</Text>
            <FormInputWithName
              name="临时位置编码"
              value={this.state.tempCode}
              _onChangeText={(text) => this.setState({ tempCode: text })}
              numberOfLines={1}
            />
            <FormInputWithName
              name="临时位置描述"
              value={this.state.tempDesc}
              _onChangeText={(text) => this.setState({ tempDesc: text })}
              numberOfLines={3}
            />
            <FormTextChoice name="安装物料编码" value={this.state.material.value} choiceMethod={this.choiceMaterial} />
            <FormText name="安装物料名称" value={this.state.material.materialName} />
          </View>
        </ScrollView>
        <TouchableOpacity style={styles.footer} onPress={() => this.confirmSub()} activeOpacity={0.8}>
          <Image
            source={require('../../../../assets/images/btn-cut-line-xxx.png')}
            style={{ width: '100%', height: 2, alignItems: 'center' }}
            resizeMode="stretch"
            resizeMethod="auto"
          />
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text style={{ color: 'white' }}>提交</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    flexDirection: 'column',
    backgroundColor: Theme.myPrimary,
  },
  footer: {
    width: '100%',
    flexDirection: 'column',
    backgroundColor: Theme.myPrimary,
    height: 48,
  },
});

export default AddPosition;
